package com.haizhi.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.codehaus.jackson.type.TypeReference;

import java.io.*;
import java.util.*;

/**
 * 读取classpath*:/conf目录下的配置文件
 * Created by chenbo on 17/4/7.
 */
public class ConfUtil {
    private static final Logger logger = LogManager.getLogger(ConfUtil.class);

    //配置文件是json
    public static Map<String, String> readJson(String confPath) {
        Map<String, String> result = new HashMap<>();
        if (confPath != null && !confPath.equals("")) {
            return JsonUtil.jsonToObject(getInputStream(confPath),
                    new TypeReference<Map<String, String>>() {
                    });
        }

        return result;
    }

    private static Reader getInputStream(String confPath) {
        Reader reader = null;
        try {
            reader = new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(confPath), "utf-8");
        } catch (UnsupportedEncodingException e) {

            logger.error("读取配置文件异常:", e);
        }

        return reader;
    }

    //配置文件一行一串字符
    public static List<String> getConfList(String confFile) {
        if (confFile == null || confFile.equals("")) {
            return Collections.emptyList();
        }
        List<String> result = new ArrayList<>();

        BufferedReader reader = new BufferedReader(getInputStream(confFile));
        try {
            String line;
            while ((line = reader.readLine()) != null) {
                //去掉空行和注释行
                if (!line.equals("") && !line.startsWith("#")) {
                    result.add(line.trim());
                }
            }
        } catch (IOException e) {
            logger.error("{}", e);
        }
        return result;
    }

    public static Set<String> getConfSet(String confFile) {
        List<String> stringList = getConfList(confFile);
        return new HashSet<>(stringList);
    }

    public static Properties getProperties(String confFile) {
        Properties props = new Properties();
        try {
            props.load(getInputStream(confFile));
        } catch (IOException e) {
            logger.error("初始化配置文件异常:", e);
            return null;
        }

        return props;
    }

}